import React, { Component } from 'react';
import { connect } from 'react-redux';
import { withConsumer } from '../../../../context';
import styles from './index.module.scss';
import classNames from 'classnames';
import { update } from '@/utils/immutableUtil';
import styled from 'styled-components';
import { Copy, RotateCw, X, ExternalLink, RefreshCw } from 'lucide-react';
import { toast } from '@/components/basicComp/Toast';


@withConsumer
@connect(({ ppt }) => ({
  fragment: ppt.fragment,
  codeResult: ppt.codeResult,
  itemIndex: ppt.itemIndex,
  currentTab: ppt.currentTab,
  openPreview: ppt.openPreview,
  previewType: ppt.previewType,
}))
class Comp extends Component {
  state = {};
  shouldComponentUpdate = (np, ns) => update.call(this, np, ns);

  handleRefresh = () => {
    window.refreshIframe?.();
  };

  handleCopyUrl = async () => {
    const { fragment } = this.props;
    try {
      var url = fragment?.url || '';
      await navigator.clipboard.writeText(url);
      toast.success('Code copied to clipboard');
    } catch (err) {
      toast.error('Failed to copy code');
    }
  };

  download(filename, content) {
    const blob = new Blob([content], { type: 'text/plain' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
    document.body.removeChild(a);
  }

  render() {
    const { fragment, codeResult, itemIndex, currentTab } = this.props;
    const {
      value: { changeState, controller },
    } = this.props;
    return (
      <div className={styles.header}>
        <div className={styles.hl}>
          <div
            className={styles.switch}
            onClick={() => {
              var newValue = currentTab === 'code' ? 'fragment' : 'code';
              changeState({
                currentTab: newValue,
              });

              if (newValue === 'fragment' && Object.keys(codeResult) == 0) {
                var Chat = controller.Chat;
                if (Chat) {
                  Chat.sandbox(fragment, itemIndex);
                }
              }
            }}
          >
            <div className={styles.switchItem} />
            <div className={styles.switchItem} />
            <div
              className={classNames(styles.slider, {
                [styles.right]: currentTab === 'fragment',
                [styles.active]: currentTab === 'fragment',
              })}
            >
              <i className="iconfont icon-daima"></i>
            </div>
          </div>
        </div>

        {currentTab === 'code' && (
          <div className={styles.hc1}>
            <button
              className={styles.button1}
              style={{ marginRight: '24px' }}
              onClick={() => {
                window.handleCopyCode?.();
              }}
            >
              Copy Code
            </button>

            <button
              className={styles.button1}
              onClick={() => {
                window.download?.();
              }}
            >
              Download Code
            </button>
          </div>
        )}
        {currentTab === 'fragment' && (
          <div className={styles.hc2}>
            <div className={styles.url}>
              <button title="Refresh" onClick={this.handleRefresh}>
                {/* <RotateCw /> */}
                <i className="iconfont icon-shuaxin"></i>
              </button>
              <span className="url-text">{fragment?.url}</span>
              <button title="Copy URL" onClick={this.handleCopyUrl}>
                <Copy />
              </button>
            </div>
            <div className={styles.urlButtons}>
              <button
                className={styles.iconButton}
                title="Open in Browser"
                onClick={() => {
                  this.download(fragment.file_path,fragment.code)
                }}
              >
                <i className="iconfont icon-xiazai"></i>
              </button>
              {/* <button
                className={styles.iconButton}
                title="Refresh"
                onClick={() => {}}
              >
                <i className="iconfont icon-fabu"></i>
              </button> */}
            </div>
          </div>
        )}

        <div className={styles.hr}>
          <div onClick={this.props.onClose} title="Close" className={styles.settingsButton}>
            <X />
          </div>
        </div>
      </div> 
    );
  }
}

export default Comp;
